| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from 'zod';
- import { RoleService } from '@/server/modules/roles/role.service';
- import { AppDataSource } from '@/server/data-source';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { RoleSchema } from '@/server/modules/roles/role.entity';
- import { authMiddleware } from '@/server/middleware/auth';
- import { AuthContext } from '@/server/types/context';
- import { logger } from '@/server/utils/logger';
- // 路径参数Schema
- const GetParamsSchema = z.object({
- id: z.coerce.number().int().positive().openapi({
- param: { name: 'id', in: 'path' },
- example: 1,
- description: '角色ID'
- })
- });
- // 路由定义
- const routeDef = createRoute({
- method: 'get',
- path: '/{id}',
- middleware: [authMiddleware],
- request: {
- params: GetParamsSchema
- },
- responses: {
- 200: {
- description: '获取角色详情成功',
- content: {
- 'application/json': {
- schema: z.object({
- code: z.number().openapi({ example: 200 }),
- message: z.string().openapi({ example: '获取角色详情成功' }),
- data: RoleSchema
- })
- }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 404: {
- description: '角色不存在',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- },
- 500: {
- description: '服务器内部错误',
- content: {
- 'application/json': { schema: ErrorSchema }
- }
- }
- },
- tags: ['角色管理']
- });
- // 创建路由实例
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const roleService = new RoleService(AppDataSource);
- const { id } = c.req.valid('param');
-
- const role = await roleService.findById(id);
-
- logger.api(`获取角色详情成功,ID: ${id}`);
- return c.json({
- code: 200,
- message: '获取角色详情成功',
- data: role
- }, 200);
- } catch (error) {
- const message = error instanceof Error ? error.message : '获取角色详情失败';
- const status = message.includes('不存在') ? 404 : 500;
-
- logger.error(`获取角色详情失败,ID: ${c.req.valid('param').id}, 错误: ${message}`);
- return c.json({
- code: status,
- message
- }, status);
- }
- });
- export default app;
|